package com.video.netty.commons.init;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.video.commons.utils.TaskUtil;
import com.video.entity.ClientMsg;
import com.video.entity.Solution;
import com.video.entity.Task;
import com.video.netty.commons.utils.ChannelUtil;
import com.video.service.client.IClientService;
import com.video.service.task.ITaskService;
import com.video.service.webcon.ISolutionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Golang服务器初始化消息
 */
@Component
public class InitHandler {

    @Autowired
    private IClientService clientService;

    @Autowired
    private ISolutionService solutionService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private ChannelUtil channelUtil;

    /**
     * 发送初始化消息
     */
    public void sendInitMsg(){
        //注册消息
        channelUtil.sendMsg("{\"id\":\"register\",\"name\":\"webserver\"}");

        //发送终端列表
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("status");
        List<ClientMsg> clientMsgs = clientService.list(queryWrapper);
        StringBuilder sb = new StringBuilder();
        sb.append("{\"id\":\"alluser\", \"users\":[");
        if(clientMsgs != null && clientMsgs.size() > 0){
            for (int i = 0; i < clientMsgs.size(); i++) {
                if(i != 0){
                    sb.append(",");
                }
                sb.append("{");
                sb.append("\"id\":\"").append(clientMsgs.get(i).getUserid()).append("\",");
                sb.append("\"terminalname\":\"").append(clientMsgs.get(i).getTerminalname()).append("\",");

                String limits = clientMsgs.get(i).getLimits();
                int n = 0;
                if(!limits.equals("0")){
                    List<Integer> integers = JSON.parseArray(limits, Integer.class);
                    for (Integer integer : integers) {
                        n += integer;
                    }
                }

                sb.append("\"limits\":").append(n);
                sb.append("}");
            }
        }
        sb.append("],");

        //处理定时音乐
        //查询所有方案
        List<Solution> solutions = solutionService.list();
        sb.append("\"timeTask\":[");
        if(solutions != null && solutions.size() > 0){

            int count = 0;
            for (int i = 0; i < solutions.size(); i++) {

                Solution solution = solutions.get(i);
                if(solution.getIsaction() == 0){
                    continue;
                }

                count++;

                if(count > 1){
                    sb.append(",");
                }

                //查询该方案的任务列表
                List<Task> tasks = taskService.queryBySolution(solution.getSolutionname(), solution.getAccount());

                sb.append("{\"solution\":\"").append(solution.getSolutionname()).append("\", \"account\":\"" + solution.getAccount()+ "\", \"task\":[");
                sb.append(taskList2Str(tasks));
                sb.append("]}");
            }
        }
        sb.append("],");

        //处理任务采集
        List<Task> tasks = taskService.queryByAccountAndTaskType(null, 2);
        sb.append("\"collectTask\":[");
        sb.append(taskList2Str(tasks));
        sb.append("],");

        //处理火警任务
        List<Task> tasks2 = taskService.queryByAccountAndTaskType(null, 3);
        sb.append("\"fireTask\":[");
        sb.append(taskList2Str(tasks2));
        sb.append("],");

        //语音合成
        List<Task> tasks3 = taskService.queryByAccountAndTaskType(null, 4);
        sb.append("\"voiceTask\":[");
        sb.append(taskList2Str(tasks3));
        sb.append("],");

        //处理一键
        ClientMsg host = clientService.getHost();
        sb.append("\"talkhost\":\"").append(host != null ? host.getUserid() : "null").append("\"");

        sb.append("}");
        channelUtil.sendMsg(sb.toString());

        //获取终端状态
        channelUtil.sendMsg("{\"id\":\"terminalStatus\"}");
    }


    /**
     * 将任务列表转换成固定格式的json字符串
     * @param tasks
     * @return
     */
    private String taskList2Str(List<Task> tasks){
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < tasks.size(); j++) {
            Task task = tasks.get(j);
            Map<String, Object> map = TaskUtil.task2Map(task);
            if(j != 0){
                sb.append(",");
            }
            sb.append(JSON.toJSONString(map));
        }
        return sb.toString();
    }


}
